package com.liang.maogouyuyin.ui.activity

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import com.liang.maogouyuyin.R
import com.liang.maogouyuyin.TheBaseApplication
import com.liang.maogouyuyin.databinding.ActivityRecordDetailBinding
import com.liang.maogouyuyin.local.LocalRepository
import com.liang.maogouyuyin.ui.adapter.PetAdapter
import com.liang.maogouyuyin.ui.adapter.RecordDetailAdapter
import com.liang.maogouyuyin.ui.viewmodel.AnomalyViewModel
import com.liang.maogouyuyin.ui.viewmodel.CasebookViewModel
import com.liang.maogouyuyin.ui.viewmodel.ExpenditureViewModel
import com.liang.maogouyuyin.ui.viewmodel.PetViewModel
import com.liang.maogouyuyin.ui.viewmodel.WeightViewModel
import com.liang.maogouyuyin.utils.DateUtil
import com.liang.maogouyuyin.widget.popup.SelectPetPopup
import com.lxj.xpopup.XPopup
import com.lxj.xpopupext.listener.TimePickerListener
import com.lxj.xpopupext.popup.TimePickerPopup
import java.util.Calendar
import java.util.Date

class RecordDetailActivity : AppCompatActivity() {
    private lateinit var binding: ActivityRecordDetailBinding

    private lateinit var petViewModel: PetViewModel
    private lateinit var expenditureViewModel: ExpenditureViewModel
    private lateinit var weightViewModel: WeightViewModel
    private lateinit var anomalyViewModel: AnomalyViewModel
    private lateinit var casebookViewModel: CasebookViewModel

    private var type = 0

    private var timestamp = -1L

    private lateinit var adapter: RecordDetailAdapter

    private lateinit var calendar: Calendar

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        binding = ActivityRecordDetailBinding.inflate(layoutInflater)
        setContentView(binding.root)

        initData()
        initView()
        initClick()
        updateUI()
    }

    override fun onResume() {
        super.onResume()
        when (type) {
            0 -> expenditureViewModel.loadExpenditureByName(LocalRepository.currentPet)
            1 -> weightViewModel.loadWeightByName(LocalRepository.currentPet)
            2 -> anomalyViewModel.loadAnomalyByName(LocalRepository.currentPet)
            3 -> casebookViewModel.loadCasebookByName(LocalRepository.currentPet)
        }
    }

    private fun initData() {
        petViewModel = TheBaseApplication.getInstance().petViewModel
        type = intent.getIntExtra("type", 0)
        when (type) {
            0 -> expenditureViewModel = TheBaseApplication.getInstance().expenditureViewModel
            1 -> weightViewModel = TheBaseApplication.getInstance().weightViewModel
            2 -> anomalyViewModel = TheBaseApplication.getInstance().anomalyViewModel
            3 -> casebookViewModel = TheBaseApplication.getInstance().casebookViewModel
        }

        calendar = Calendar.getInstance()
        timestamp = DateUtil.getStartTimestampForMonth(calendar.time)
    }

    private fun initView() {
        val endTimestamp = timestamp + 86400000L * DateUtil.getDaysForMonth(Date(timestamp))

        binding.recordDetailTitle.text = petViewModel.pet.value?.name

        binding.recordDetailPickerText.text = DateUtil.formatTimeStamp(calendar.timeInMillis, "yyyy年M月")

        when (type) {
            0 -> {
                binding.recordDetailAdd.text = getString(R.string.record_detail_add_bill)
                val list = expenditureViewModel.expenditureList.value?.filter { it.date in timestamp..endTimestamp } as ArrayList
                binding.recordDetailSum.text = String.format(getString(R.string.record_detail_bill_sum), list.sumOf { it.money.toDouble() })
            }
            1 -> {
                val list = weightViewModel.weightList.value
                binding.recordDetailSumText.text = getString(R.string.record_detail_weight)
                binding.recordDetailSumTitle.text = getString(R.string.record_detail_weight)
                if (!list.isNullOrEmpty()) {
                    binding.recordDetailSum.text = String.format(getString(R.string.record_detail_weight_sum), list[0].weight)
                    binding.recordDetailSumTitle.text = DateUtil.formatTimeStamp(list[0].date)
                }
            }
            else -> {
                binding.recordDetailSumLayout.visibility = View.GONE
            }
        }

        binding.recordDetailRecyclerview.layoutManager = LinearLayoutManager(this)
        adapter = RecordDetailAdapter(this)
        adapter.setType(type)
        when (type) {
            0 -> adapter.setList(expenditureViewModel.expenditureList.value!!.filter { it.date in timestamp..endTimestamp } as ArrayList)
            1 -> adapter.setList(weightViewModel.weightList.value!!.filter { it.date in timestamp..endTimestamp } as ArrayList)
            2 -> adapter.setList(anomalyViewModel.anomalyList.value?.filter { it.date in timestamp..endTimestamp } as ArrayList)
            3 -> adapter.setList(casebookViewModel.casebookList.value?.filter { it.date in timestamp..endTimestamp } as ArrayList)
        }
        binding.recordDetailRecyclerview.adapter = adapter
    }

    private fun initClick() {
        binding.recordDetailToolBar.setNavigationOnClickListener {
            finish()
        }

        binding.recordDetailTitle.setOnClickListener {
            XPopup.Builder(this)
                .asCustom(SelectPetPopup(this)
                    .setList(petViewModel.petList.value!!)
                    .setListener(object: PetAdapter.SelectListener{
                        @SuppressLint("NotifyDataSetChanged")
                        override fun select(petName: String) {
                            binding.recordDetailTitle.text = petName
                            when (type) {
                                0 -> expenditureViewModel.loadExpenditureByName(petName)
                                1 -> weightViewModel.loadWeightByName(petName)
                                2 -> anomalyViewModel.loadAnomalyByName(petName)
                                3 -> casebookViewModel.loadCasebookByName(petName)
                                else -> {}
                            }
                        }
                    })
                ).show()
        }

        binding.recordDetailPicker.setOnClickListener {
            XPopup.Builder(this)
                .asCustom(TimePickerPopup(this)
                    .setMode(TimePickerPopup.Mode.YM)
                    .setDefaultDate(calendar)
                    .setDateRange(null, calendar)
                    .setTimePickerListener(object:TimePickerListener{
                        override fun onTimeChanged(date: Date?) {}

                        override fun onTimeConfirm(date: Date?, view: View?) {
                            binding.recordDetailPickerText.text = DateUtil.formatTimeStamp(date!!.time, "yyyy年M月")
                            timestamp = DateUtil.getStartTimestampForMonth(date)
                            when (type) {
                                0 -> expenditureViewModel.loadExpenditureByName(LocalRepository.currentPet)
                                1 -> weightViewModel.loadWeightByName(LocalRepository.currentPet)
                                2 -> anomalyViewModel.loadAnomalyByName(LocalRepository.currentPet)
                                3 -> casebookViewModel.loadCasebookByName(LocalRepository.currentPet)
                                else -> {}
                            }
                        }

                        override fun onCancel() {}
                    })
                ).show()
        }

        binding.recordDetailAdd.setOnClickListener {
            val intent = Intent(this, AddDetailActivity::class.java)
            intent.putExtra("type", type)
            startActivity(intent)
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun updateUI() {

        when (type) {
            0 -> {
                expenditureViewModel.expenditureList.observe(this) { beans ->
                    val endTimestamp = timestamp + 86400000L * DateUtil.getDaysForMonth(Date(timestamp))
                    val list = beans.filter { it.date in timestamp..endTimestamp } as ArrayList
                    if (list.isNotEmpty())
                        binding.recordDetailSum.text = String.format(getString(R.string.record_detail_bill_sum), list.sumOf { it.money.toDouble() })
                    else
                        binding.recordDetailSum.text = ""
                    adapter.setList(list)
                    adapter.notifyDataSetChanged()
                }
            }
            1 -> {
                weightViewModel.weightList.observe(this) { beans ->
                    val endTimestamp = timestamp + 86400000L * DateUtil.getDaysForMonth(Date(timestamp))
                    val list = beans.filter { it.date in timestamp..endTimestamp } as ArrayList
                    if (list.isNotEmpty())
                        binding.recordDetailSum.text = String.format(getString(R.string.record_detail_weight_sum), list[0].weight)
                    else
                        binding.recordDetailSum.text = ""
                    adapter.setList(list)
                    adapter.notifyDataSetChanged()
                }
            }
            2 -> {
                anomalyViewModel.anomalyList.observe(this) { beans ->
                    val endTimestamp = timestamp + 86400000L * DateUtil.getDaysForMonth(Date(timestamp))
                    val list = beans.filter { it.date in timestamp..endTimestamp } as ArrayList
                    adapter.setList(list)
                    adapter.notifyDataSetChanged()
                }

            }
            3 -> {
                casebookViewModel.casebookList.observe(this) { beans ->
                    val endTimestamp = timestamp + 86400000L * DateUtil.getDaysForMonth(Date(timestamp))
                    val list = beans.filter { it.date in timestamp..endTimestamp } as ArrayList
                    adapter.setList(list)
                    adapter.notifyDataSetChanged()
                }
            }
        }
    }
}